/**
 * 图片相关接口
 */

import { getApiBaseUrl } from '@/utils/env'

const BASE_URL = getApiBaseUrl()

/**
 * 获取图片列表
 * @param {Object} params 请求参数
 * @param {number} params.page 页码
 * @param {number} params.pageSize 每页数量
 * @param {string} params.category 分类
 * @returns {Promise}
 */
export function getImageList(params = {}) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}/api/images/list`,
      method: "GET",
      data: {
        page: params.page || 1,
        pageSize: params.pageSize || 20,
        category: params.category === "all" ? undefined : params.category, // all 时不传 category
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 后端可能返回两种格式：
          // 1. 包装格式: { code: 200, message: 'success', data: { list, total, page, pageSize } }
          // 2. 直接格式: { list, total, page, pageSize }
          const response = res.data;
          
          // 检查是否是包装格式
          if (response && typeof response === 'object' && response.code === 200 && response.data) {
            // 包装格式
            resolve({
              code: 200,
              data: response.data
            });
          } else if (response && typeof response === 'object' && response.list !== undefined) {
            // 直接格式，有 list 字段，说明是图片列表数据
            resolve({
              code: 200,
              data: response
            });
          } else {
            // 其他情况，尝试直接返回
            resolve({
              code: 200,
              data: response
            });
          }
        } else {
          reject(new Error(`请求失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

/**
 * 获取分类列表
 * @returns {Promise}
 */
export function getCategoryList() {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}/api/images/category`,
      method: "GET",
      success: (res) => {
        if (res.statusCode === 200) {
          // 后端可能返回两种格式：
          // 1. 包装格式: { code: 200, message: 'success', data: [{ id, name, slug, count }] }
          // 2. 直接格式: [{ id, name, slug, count }]
          const response = res.data;
          let categoryList = [];
          
          // 检查是否是包装格式
          if (response && typeof response === 'object' && response.code === 200 && Array.isArray(response.data)) {
            categoryList = response.data;
          } else if (Array.isArray(response)) {
            // 直接格式，是数组
            categoryList = response;
          } else if (response && Array.isArray(response.data)) {
            categoryList = response.data;
          } else {
            reject(new Error('分类数据格式错误'));
            return;
          }
          
          // 添加 "全部" 分类到列表开头，并将分类 id 转换为可用于筛选的格式
          const categories = [
            { id: "all", name: "全部", slug: "all", count: 0 },
            ...categoryList.map(cat => ({
              id: cat.slug || cat.id, // 使用 slug 作为 id，如果没有则使用数字 id
              name: cat.name,
              slug: cat.slug,
              count: cat.count || 0
            }))
          ];
          // 计算总数（排除"全部"项）
          const totalCount = categoryList.reduce((sum, cat) => sum + (cat.count || 0), 0);
          categories[0].count = totalCount;
          
          resolve({
            code: 200,
            data: categories
          });
        } else {
          reject(new Error(`请求失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

/**
 * 获取图片详情
 * @param {string|number} id 图片ID
 * @returns {Promise}
 */
export function getImageDetail(id) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}/api/images/${id}`,
      method: "GET",
      success: (res) => {
        if (res.statusCode === 200) {
          // 后端可能返回两种格式：
          // 1. 包装格式: { code: 200, message: 'success', data: { id, title, url, ... } }
          // 2. 直接格式: { id, title, url, ... }
          const response = res.data;
          let image = null;
          
          // 检查是否是包装格式
          if (response && typeof response === 'object' && response.code === 200 && response.data) {
            image = response.data;
          } else if (response && typeof response === 'object' && response.id !== undefined) {
            // 直接格式，有 id 字段，说明是图片对象
            image = response;
          } else {
            reject(new Error('图片数据格式错误'));
            return;
          }
          
          // 转换后端字段到前端需要的格式
          resolve({
            code: 200,
            data: {
              id: image.id,
              title: image.title,
              thumbnail: image.thumbnail || image.url,
              image: image.url, // 后端使用 url 字段
              category: image.categoryId || (image.category && image.category.slug) || "all",
              width: image.width,
              height: image.height,
              views: image.views || 0,
              likes: image.likes || 0,
              createTime: image.createdAt
            }
          });
        } else if (res.statusCode === 404) {
          reject(new Error('图片不存在'));
        } else {
          reject(new Error(`请求失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

/**
 * 搜索图片
 * @param {Object} params 请求参数
 * @param {string} params.keyword 关键词
 * @param {number} params.page 页码
 * @param {number} params.pageSize 每页数量
 * @returns {Promise}
 */
export function searchImages(params = {}) {
  return new Promise((resolve, reject) => {
    if (!params.keyword || params.keyword.trim() === "") {
      reject(new Error('关键词不能为空'));
      return;
    }
    
    uni.request({
      url: `${BASE_URL}/api/images/search`,
      method: "GET",
      data: {
        keyword: params.keyword.trim(),
        page: params.page || 1,
        pageSize: params.pageSize || 20,
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 后端可能返回两种格式：
          // 1. 包装格式: { code: 200, message: 'success', data: { list, total, page, pageSize } }
          // 2. 直接格式: { list, total, page, pageSize }
          const response = res.data;
          
          // 检查是否是包装格式
          if (response && typeof response === 'object' && response.code === 200 && response.data) {
            // 包装格式
            resolve({
              code: 200,
              data: response.data
            });
          } else if (response && typeof response === 'object' && response.list !== undefined) {
            // 直接格式，有 list 字段
            resolve({
              code: 200,
              data: response
            });
          } else {
            // 其他情况，尝试直接返回
            resolve({
              code: 200,
              data: response
            });
          }
        } else {
          reject(new Error(`请求失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

/**
 * 模拟数据（开发阶段使用）
 */
export function getMockImageList(params = {}) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const page = params.page || 1;
      const pageSize = params.pageSize || 20;
      const list = [];

      for (let i = 0; i < pageSize; i++) {
        const id = (page - 1) * pageSize + i + 1;
        list.push({
          id: id,
          title: `美女图片 ${id}`,
          thumbnail: `https://picsum.photos/400/600?random=${id}`,
          image: `https://picsum.photos/800/1200?random=${id}`,
          category: params.category || "all",
          width: 800,
          height: 1200,
          views: Math.floor(Math.random() * 10000),
          likes: Math.floor(Math.random() * 1000),
          createTime: new Date().toISOString(),
        });
      }

      resolve({
        code: 200,
        data: {
          list: list,
          total: 1000,
          page: page,
          pageSize: pageSize,
        },
      });
    }, 500);
  });
}

/**
 * 模拟分类数据
 */
export function getMockCategoryList() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        data: [
          { id: "all", name: "全部", count: 1000 },
          { id: "cute", name: "可爱", count: 200 },
          { id: "sexy", name: "性感", count: 300 },
          { id: "pure", name: "清纯", count: 250 },
          { id: "fashion", name: "时尚", count: 150 },
          { id: "sweet", name: "甜美", count: 100 },
        ],
      });
    }, 300);
  });
}
